import { defineStore } from 'pinia'
import { ref } from 'vue'
import { computed } from 'vue'
import { useUserStore } from './user'
import { inserCartAPI, getCartListAPI, delCartAPI } from '@/apis/cart'
export const useCartStore = defineStore('cart', () =>{
    const userStore = useUserStore()
    const isLogin = computed(() => userStore.userInfo.token)
    // 1. 定义 state - cartList
    const cartList = ref([])
    
    // 更新购物车数据
    const updateCart = async () => {
        const res = await getCartListAPI()
        cartList.value = res.result
    }

    // 2. 定义 action - addCart
    const addCart = async (goods) => {
        const { skuId, count } = goods
        if(isLogin.value) {
            // 登录状态，发送请求
            await inserCartAPI({ skuId, count })
            updateCart()
        } else {
            // 添加购物车操作
            const item = cartList.value.find((item) => goods.skuId === item.skuId) 
            if (item) {
                item.count += 1
            } else {
                cartList.value.push(goods)
            }
        }
    }

    // 删除购物车
    const delCart = async (skuId) => {
        if (isLogin.value) {
            await delCartAPI([skuId])
            updateCart()
        } else {
            cartList.value = cartList.value.filter((item) => item.skuId !== skuId)
        }
    }

    // 清除购物车数据
    const clearCart = async () => {
        cartList.value = []
    }

    // 单选
    const singleCheck = (skuId, selected) => {
        const item = cartList.value.find((item) => item.skuId === skuId)
        if (item) {
            item.selected = selected
        }
    }

    // 全选功能
    const allChecked = (selected) => {
        cartList.value.forEach((item) => item.selected = selected)
    }

    // 计算属性
    // 1. 总数
    const allCount = computed(() => cartList.value.reduce((a, c) => a + c.count, 0))
    // 2. 总价
    const allPrice = computed(() => cartList.value.reduce((a, c) => a + c.count * c.price, 0))
   
    // 是否全选
    const allCheck = computed(() => cartList.value.every((item) => item.selected))

    // 选中的商品数量
    const checkedCount = computed(() => cartList.value.reduce((a, c) => a + (c.selected ? c.count : 0), 0))
    // 选中商品的总价
    const checkedPrice = computed(() => cartList.value.reduce((a, c) => a + (c.selected ? c.count * c.price : 0), 0))
    return { 
        cartList, 
        addCart,
        delCart,
        allCount,
        allPrice,
        singleCheck,
        allCheck,
        allChecked,
        checkedCount,
        checkedPrice,
        clearCart,
        updateCart
    }
}, {
    persist: true
}
)